﻿#region <!-- Using Directives -->

using System;
using System.IO;

#endregion

namespace WordSharpDev.Extensions
{
	internal static class FileExtensions
	{
		#region <!-- FromCurrentPath -->

		public static String FromCurrentPath(this String p_RelativePath)
		{
			return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p_RelativePath);
		}

		#endregion

		#region <!-- AsDirectory -->

		public static DirectoryInfo AsDirectory(this String p_DirectoryPath)
		{
			if (p_DirectoryPath == null) return null;

			return new DirectoryInfo(p_DirectoryPath);
		}

		#endregion

		#region <!-- AsFile -->

		public static FileInfo AsFile(this String p_FilePath)
		{
			if (p_FilePath == null) return null;

			return new FileInfo(p_FilePath);
		}

		#endregion

		#region <!-- ReadFile -->

		public static Byte[] ReadFile(this String p_FilePath)
		{
			if (p_FilePath == null) return null;

			using (var l_Stream = new FileStream(p_FilePath, FileMode.Open, FileAccess.Read))
			{
				var l_Result = new Byte[l_Stream.Length];

				var l_Remaining = (Int32)l_Stream.Length;

				var l_Read = (Int32)0;

				while (0 < l_Remaining)
				{
					//> Read may return anything from 0 to l_Remaining
					var n = l_Stream.Read(l_Result, l_Read, l_Remaining);

					//> Break when the end of the file is reached
					if (n == 0) break;

					l_Remaining -= n;
					l_Read += n;
				}

				return l_Result;
			}
		}

		#endregion

		#region <!-- WriteFile -->

		public static void WriteFile(this String p_Target, FileInfo p_File)
		{
			if (p_File == null) return;
			if (p_Target == null) return;

			if (!p_File.Directory.Exists)
				p_File.Directory.Create();

			using (var l_Stream = p_File.CreateText())
			{
				l_Stream.Write(p_Target);
			}
		}

		public static void WriteFile(this String p_Target, String p_Path)
		{
			if (p_Path == null) return;
			if (p_Target == null) return;

			var l_File = new FileInfo(p_Path);

			WriteFile(p_Target, l_File);
		}

		#endregion
	}
}